var designClass = "design_class", hideClass = "hide_class", browseClass = "browse_class", addClass = "add_class", editClass = "edit_class";
var upWindow = window.parent.frames["zwIframe"];
if (!upWindow) {
	upWindow = window.parent.frames["componentDiv"].frames["zwIframe"];
}
function fy_dialog_close() {
	// window.parent.$(".mask").remove();
	// window.parent.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger("click");
	window.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger(
			"click");
}

function getUpFields(name) {
	return upWindow.$("[validate*='name:\"" + name + "\"']");
}
function getUpFieldsByFieldval(name) {
	return upWindow.$("[fieldval*='displayName:\"" + name + "\"']");
}

function addOrDelRepeat(name, newLength) {
	var fields = getUpFieldsByFieldval(name);
	var oldLength = fields.length;
	var tbody = getUpFieldsByFieldval(name).eq(0).parent();
	while (!tbody.is("tbody")) {
		tbody = tbody.parent();
	}
	for ( var i = 0, length = Math.abs(newLength - oldLength); i < length; i++) {
		if (newLength > oldLength) {
			upWindow.fy_addEmpty(tbody.children().last());
		} else {
			upWindow.fy_delCurrentRepeat(tbody.children().last());
		}
	}
}

function getUpFieldValue(field) {
	var fieldVal = field.attr("fieldVal");
	var editTag = field.hasClass(editClass);
	var browseTag = field.hasClass(browseClass);
	var addTag = field.hasClass(addClass);
	if (fieldVal != null && typeof (fieldVal) != 'undefined') {
		fieldVal = eval("(" + fieldVal + ")");
	} else {
		return null;
	}
	var obj = new Object();
	obj.displayName = fieldVal.displayName;
	obj.name = fieldVal.name;
	var tag = true;
	switch (fieldVal.inputType) {
	case "text":
	case "textarea":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		} else if (addTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		}
		break;
	case "checkbox":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		}
		break;
	case "radio":
		if (editTag) {
			obj.value = field.find(":radio:checked").attr("val4cal");
		} else if (browseTag) {
			obj.value = field.find(":radio:checked").attr("val4cal");
		}
		break;
	case "select":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name + " option:selected")
					.attr("val4cal");
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).attr("val4cal");
		}
		break;
	case "date":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
			if (obj.value != "") {
				obj.value = obj.value + " 00:00";
			}
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "datetime":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "flowdealoption":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		} else if (addTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "lable":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "relationform":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "relation":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "project":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "member":
	case "multimember":
	case "account":
	case "multiaccount":
	case "department":
	case "multidepartment":
	case "post":
	case "multipost":
	case "level":
	case "multilevel":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name + "_txt").val();
			obj.id = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).text();
		}
		break;
	case "attachment":
	case "image":
	case "document":
		if (editTag || browseTag) {
			var attNames = "";
			var tempField = field.find("#" + fieldVal.name);
			var tempFileId = "";
			if (tempField[0].tagName.toLowerCase() == "input") {
				tempFileId = tempField.val();
			} else if (tempField[0].tagName.toLowerCase() == "span") {
				tempFileId = tempField[0].innerHTML;
			}
			var atts = upWindow.getAttBySubreference(tempFileId);
			for ( var j = 0; j < atts.length; j++) {
				attNames += atts[j].filename + ",";
			}
			if (attNames != "") {
				attNames = attNames.substr(0, attNames.length - 1);
			}
			obj.value = attNames;
		}
		break;
	case "outwrite":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "externalwrite-ahead":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "exchangetask":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "querytask":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	default:
		tag = false;
	}
	if (obj.value != undefined) {
		obj.value = obj.value.replace("\r\n", ";");
		obj.value = obj.value.replace("\n", ";");
	}
	return obj;
}
function setUpFieldValue(name, value) {
	upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input").val(
			value);
	upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input")
			.trigger("blur");
}

function setUpFieldValue2(field, value, displayValue, index) {
	var fieldVal = field.attr("fieldVal");
	var editTag = field.hasClass(editClass);
	var addTag = field.hasClass(addClass);
	value = trim(value);
	displayValue = trim(displayValue);
	if (fieldVal != null && typeof (fieldVal) != 'undefined') {
		fieldVal = eval("(" + fieldVal + ")");
	} else {
		return null;
	}

	var tag = true;
	switch (fieldVal.inputType) {
	case "text":
	case "textarea":
		if (editTag) {
			var inField = field.find("#" + fieldVal.name);
			inField.val(value);
			inField.trigger("blur");
		} else if (addTag) {
			var inField = field.find("#" + fieldVal.name);
			inField.val(value);
			inField.trigger("blur");
		}
		break;
	case "checkbox":
		if (editTag) {
			field.find("#" + fieldVal.name).attr("checked", true);
			field.find("#" + fieldVal.name).trigger("click");
		}
		break;
	case "radio":
		if (editTag) {
			field.find(":radio").eq(value).attr("checked", true);
			field.find(":radio").eq(value).trigger("click");
		}
		break;
	case "select":
		if (editTag) {
			var options = field.find("#" + fieldVal.name + " option");
			for ( var k = 0; k < options.length; k++) {
				if (options.eq(k).text() == value)
					options.eq(k).attr("selected", true);
			}
			field.find("#" + fieldVal.name).trigger("change");
		}
		break;
	case "date":
		if (editTag) {
			field.find("#" + fieldVal.name).val(value);
			field.find("#" + fieldVal.name).trigger("blur");
		}
		break;
	case "datetime":
		if (editTag) {
			field.find("#" + fieldVal.name).val(value);
			field.find("#" + fieldVal.name).trigger("blur");
		}
		break;
	case "member":
	case "multimember":
	case "account":
	case "multiaccount":
	case "department":
	case "multidepartment":
	case "post":
	case "multipost":
	case "level":
	case "multilevel":
		if (editTag) {
			alert(editTag);
			field.find("#" + fieldVal.name + "_txt").val(value);
		}
		break;
	}
}

/**
 * 去除左右空格
 */
function trim(str) {
	return (str) ? (typeof str == "string" ? str.replace(/^\s*/, "").replace(
			/\s*$/, "") : str) : "";
}

/**
 * 
 * 
 * @param code
 *            供应商编码
 * @param queryType
 *            查询类型 1:仅查询供应商名称 2: 查询供应商名称和供应商基本信息
 * @param operator
 *            处理方法
 */
function _ajax(code, queryType, operator) {
	document.getElementById("lodingDiv").style.display = '';
	var xmlhttp = null;
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	document.getElementById("lodingDiv").style.display = '';
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				text = xmlhttp.responseText;
				if (text == 1) {
					alert("不存在供应商编码：" + code);
				} else if (text == 2) {
					alert("用户还未登陆，或者已掉线");
				} else if (text == 3) {
					alert("供应商编码不能为空。");
				} else {
					operator(eval("(" + text + ")"));
				}
			} else {
				alert("连接服务器异常");
			}
			document.getElementById("lodingDiv").style.display = 'none';
		}
	};
	xmlhttp.open("get",
			"./oa2uapController.do?method=findProviderInfoByCode&code=" + code
					+ "&type=" + queryType + "&temp=" + Math.random(), true);
	xmlhttp.send();
}

function getStringLength(str) {
	var len = 0;
	for ( var i = 0; i < str.length; i++) {
		var c = str.charCodeAt(i);
		// 单字节加1
		if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
			len++;
		} else {
			len += 3;
		}
	}
	return len;
}

var fieldNameMap = {
	address : "企业地址",
	linkman : "联系人",
	supplyCycle : "供货周期",
	cvenbank : "结算银行",
	supplyAddress : "发货地址",
	tel : "电话号码",
	cpurbillcode : "发票税码",
	bankAccount : "银行账号",
	taxRegister : "税务登记号",
	fax : "传真号码",
	couttype : [ "物流方式", "物流方式PK" ],
	cmoneytype : [ "币种", "币种PK" ],
	qualitySystem : "质量体系",
	postCode : "邮编",
	companyType : [ "企业类型", "企业类型PK" ],
	ccuspaycond : "付款条件",
	property : "属性",
	email : "电子邮箱",
	ccontent : "价格条款",
	fax : "传真号码",
	cVenBankMemo : "开户银行",
	bankAccountName : "银行开户名",
	bankCode : "银行代码"
/*
 * , qylb : '企业类别', zczj : '注册资金', clsj : '成立时间', zgrs : '职工总人数', jycs : '经营场所',
 * frdb : '法人代表', frdbsfz : '法人代表身份证', nxse : '年销售额'
 */
};

var inputLengthMap = {
	address : 100,
	linkman : 20,
	supplyCycle : 20,
	cvenbank : 100,
	supplyAddress : 100,
	tel : 20,
	cpurbillcode : 20,
	bankAccount : 50,
	taxRegister : 20,
	fax : 20,
	qualitySystem : 20,
	postCode : 20,
	ccuspaycond : 100,
	property : 1,
	email : 100,
	ccontent : 100,
	fax : 20,
	cVenBankMemo : 100,
	bankAccountName : 50,
	bankCode : 50
};

function checkInputLength() {
	for ( var key in inputLengthMap) {
		var length = getStringLength(document.getElementsByName(key)[0].value);
		if (length > inputLengthMap[key]) {
			alert(fieldNameMap[key].replace("", "") + "字符长度超过"
					+ inputLengthMap[key]);
			return false;
		}
	}
	return true;
}

/**
 * 检查供应商名称是否符合规定,并把小写字母改成大写，把全角字符改成半角
 * 
 * @param field
 * @returns {Boolean}
 */
function checkAndReplaceProviderName(field) {
	var isRight = false;

	var charlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	charlist += "abcdefghijklmnopqrstuvwxyz";
	charlist += "0123456789";
	charlist += " `~!@#$%^&*()_+-={}|[]\:\\\";'<>?,./";// 半角空格

	var providerName = field.value;
	var result = "";
	for ( var i = 0; i < providerName.length; i++) {
		var c1 = providerName.charAt(i);
		var c2 = providerName.charCodeAt(i);
		if ("　" == c1) {
			result += " ";
		} else if ("，" == c1) {
			result += ",";
		} else if ("。" == c1) {
			result += ".";
		} else {
			if (charlist.indexOf(String.fromCharCode(c2 - 65248)) > -1) {
				result += String.fromCharCode(c2 - 65248);
			} else {
				result += c1;
			}
		}
	}

	field.value = trim(result.toUpperCase());
	isRight = true;

	return isRight;
}

var ccontentValueArray = [ "出厂价", "到库价", "FOB", "CIF", "C&F", "其他" ];
var ccuspaycondValueArray = [ "票后30天", "票后45天", "票后60天", "票后70天", "其他" ];
function isExistInArray(array, value) {
	for ( var i in array) {
		if (array[i] == value) {
			return i;
		}
	}
	return -1;
}
function setCcontentAndCcuspaycond() {
	var ccontentValue = document.getElementsByName('ccontent')[0].value;
	var ccuspaycondValue = document.getElementsByName('ccuspaycond')[0].value;
	var ccontentIndex = (ccontentValue == '' ? 0 : isExistInArray(
			ccontentValueArray, ccontentValue));
	var ccuspaycondIndex = (ccuspaycondValue == '' ? 0 : isExistInArray(
			ccuspaycondValueArray, ccuspaycondValue));

	if (ccontentValue == '') {
		document.getElementsByName('ccontent')[0].value = ccontentValueArray[0];
	}

	if (ccuspaycondValue == '') {
		document.getElementsByName('ccuspaycond')[0].value = ccuspaycondValueArray[0];
	}

	if (ccontentIndex == -1) {
		ccontentIndex = 5;
		document.getElementById("ccontentDiv").style.display = '';
	} else {
		document.getElementById("ccontentDiv").style.display = 'none';
	}

	if (ccuspaycondIndex == -1) {
		ccuspaycondIndex = 4;
		document.getElementById("ccuspaycondDiv").style.display = '';
	} else {
		document.getElementById("ccuspaycondDiv").style.display = 'none';
	}
	document.getElementsByName("ccontentSelect")[0].value = ccontentIndex;
	document.getElementsByName("ccuspaycondSelect")[0].value = ccuspaycondIndex;
}
function setCcontentAndCcuspaycondDisabled() {
	document.getElementsByName('ccontent')[0].value = '';
	document.getElementsByName('ccuspaycond')[0].value = '';
	document.getElementById("ccontentDiv").style.display = 'none';
	document.getElementById("ccuspaycondDiv").style.display = 'none';
	document.getElementsByName("ccontentSelect")[0].selectedIndex = -1;
	document.getElementsByName("ccuspaycondSelect")[0].selectedIndex = -1;
};

function onCcontentSelectChange(node) {
	if (node.value == 5) {
		document.getElementById("ccontentDiv").style.display = '';
		document.getElementsByName('ccontent')[0].value = '';
	} else {
		document.getElementById("ccontentDiv").style.display = 'none';
		document.getElementsByName('ccontent')[0].value = ccontentValueArray[node.value];
	}
}

function onCcuspaycondSelectChange(node) {
	if (node.value == 5) {
		document.getElementById("ccuspaycondDiv").style.display = '';
		document.getElementsByName('ccuspaycond')[0].value = '';
	} else {
		document.getElementById("ccuspaycondDiv").style.display = 'none';
		document.getElementsByName('ccuspaycond')[0].value = ccuspaycondValueArray[node.value];
	}
}

function ProviderInformation() {

	/**
	 * 检测不存在为空的项
	 */
	this.checkNotNull = function() {
		for ( var name in fieldNameMap) {
			var node = document.getElementsByName(name)[0];
			if (typeof fieldNameMap[name] === 'string') {
				if (node.value.replace(/ /g, '') === '') {
					alert(fieldNameMap[name].replace('', '') + "字段不能为空");
					return false;
				}
			} else {
				if (node.value.replace(/ /g, '') === '') {
					alert(fieldNameMap[name][0].replace('', '') + "字段不能为空");
					return false;
				}
			}
		}
		return true;
	};

	/**
	 * 将弹出窗口的供应商的详细信息返回表单
	 */
	this.setValuesToForm = function() {
		for ( var name in fieldNameMap) {
			var node = document.getElementsByName(name)[0];
			if (typeof fieldNameMap[name] === 'string') {
				
				if (name == 'property') {
					setUpFieldValue2(getUpFieldsByFieldval(
							fieldNameMap[name]).eq(0), (document
							.getElementsByName(name)[0].value == '0' ? 'D'
							: 'F'));
				} else
					setUpFieldValue2(getUpFieldsByFieldval(
							fieldNameMap[name]).eq(0), node.value);
			} else {
				setUpFieldValue2(getUpFieldsByFieldval(fieldNameMap[name][1])
						.eq(0), node.value);
				setUpFieldValue2(getUpFieldsByFieldval(
						fieldNameMap[name][0]).eq(0),
						node.options[node.selectedIndex].text);
			}
		}
	};

	/**
	 * 设置值
	 */
	this.setValues = function(values) {
		if (values) {
			for ( var name in fieldNameMap) {
				if (name == 'property') {
					document.getElementsByName(name)[0].value = (getUpFieldValue(getUpFieldsByFieldval(
							fieldNameMap[name]).eq(0)).value == 'D' ? '0' : '1');
				} else
					document.getElementsByName(name)[0].value = values[name] ? values[name]
							: "";
			}
		} else {
			for ( var name in fieldNameMap) {
				document.getElementsByName(name)[0].value = "";
			}
		}

		setCcontentAndCcuspaycond();
	};

	/**
	 * 输入框disabled状态
	 */
	this.setFieldsDisabled = function() {
		for ( var name in fieldNameMap) {
			document.getElementsByName(name)[0].className = "disabledInput";
			document.getElementsByName(name)[0].disabled = true;
		}
		document.getElementsByName("ccontentSelect")[0].className = 'disabledInput';
		document.getElementsByName("ccontentSelect")[0].disabled = true;
		document.getElementsByName("ccuspaycondSelect")[0].className = 'disabledInput';
		document.getElementsByName("ccuspaycondSelect")[0].disabled = true;
	};

	/**
	 * 输入框readOnly状态
	 */
	this.setFieldsReadOnly = function() {
		for ( var name in fieldNameMap) {
			var field = document.getElementsByName(name)[0];
			if (field.tagName.toUpperCase() === 'SELECT') {
				field.disabled = true;
			} else {
				field.disabled = false;
				field.readOnly = "readonly";
			}
			field.className = "readOnlyInput";
		}

		document.getElementsByName("ccontentSelect")[0].className = 'readOnlyInput';
		document.getElementsByName("ccontentSelect")[0].disabled = true;
		document.getElementsByName("ccuspaycondSelect")[0].className = 'readOnlyInput';
		document.getElementsByName("ccuspaycondSelect")[0].disabled = true;
	};
	/**
	 * 输入框可输入状态
	 */
	this.setFieldsFill = function() {
		for ( var name in fieldNameMap) {
			var field = document.getElementsByName(name)[0];
			field.className = "manualInput";
			field.readOnly = false;
			field.disabled = false;
		}

		document.getElementsByName("ccontentSelect")[0].className = 'manualInput';
		document.getElementsByName("ccontentSelect")[0].readOnly = false;
		document.getElementsByName("ccontentSelect")[0].disabled = false;
		document.getElementsByName("ccuspaycondSelect")[0].className = 'manualInput';
		document.getElementsByName("ccuspaycondSelect")[0].readOnly = false;
		document.getElementsByName("ccuspaycondSelect")[0].disabled = false;
	};

	/**
	 * 初始化输入框的值，从表单中读取
	 */
	this.initValues = function() {
		for ( var name in fieldNameMap) {
			if (typeof fieldNameMap[name] === 'string') {
				if (name == 'property') {
					document.getElementsByName(name)[0].value = (getUpFieldValue(getUpFieldsByFieldval(
							fieldNameMap[name]).eq(0)).value == 'D' ? '0' : '1');
				} else
					document.getElementsByName(name)[0].value = getUpFieldValue(getUpFieldsByFieldval(
							fieldNameMap[name]).eq(0)).value;
			} else {
				document.getElementsByName(name)[0].value = getUpFieldValue(getUpFieldsByFieldval(
						fieldNameMap[name][1]).eq(0)).value;
			}
		}
		setCcontentAndCcuspaycond();
	};

	this.initValues();
};
/**
 * 单选按钮
 * 
 * @param name
 *            弹出窗口中单选按钮的name
 * @param fName
 *            表单中显示的文本
 * @param fRadioName
 *            表单中的单选框
 * @param fTextArray
 *            显示的文本的列表
 * @returns void
 */
function RadioField(name, fName, fRadioName, fTextArray) {
	this.fieldName = null;
	var form_fieldName = null;
	var form_radioName = null;
	var form_textArray = null;
	var _this = this;

	/**
	 * 初始化单选按钮的值，从表单中读取
	 */
	var initValues = function() {
		var nodes = document.getElementsByName(_this.fieldName);
		var fNodes = getUpFieldsByFieldval(form_radioName);
		var checkedIndex = getUpFieldValue(fNodes.eq(0)).value;
		if (checkedIndex)
			nodes[getUpFieldValue(fNodes.eq(0)).value].checked = true;
		// for ( var i = 0, length = nodes.length; i < length; i++) {
		// try {
		// nodes[i].checked = fNodes[i].checked;
		// } catch (e) {
		// alert(nodes[i].name);
		// alert(fNodes[i].name);
		// }
		// }
	};

	this.getName = function() {
		return _this.fieldName;
	};
	/**
	 * 将弹出窗口的单选按钮的值返回表单
	 */
	this.setValueToForm = function() {
		var nodes = document.getElementsByName(_this.fieldName);
		console.info("form_radioName="+form_radioName)
		var fNodes = getUpFieldsByFieldval(form_radioName);
		for ( var i = 0, length = nodes.length; i < length; i++) {
//			fNodes[i].checked = nodes[i].checked;
			if (form_fieldName && nodes[i].checked) {
				setUpFieldValue2(getUpFieldsByFieldval(form_fieldName).eq(0),
						form_textArray[i]);
			}
			if (nodes[i].checked) {
				setUpFieldValue2(fNodes.eq(0),i);
			}
		}
	};

	/**
	 * 获取单选框的值
	 */
	this.getValue = function() {
		var nodes = document.getElementsByName(_this.fieldName);
		var value = -1;
		for ( var i = 0, length = nodes.length; i < length; i++) {
			if (nodes[i].checked) {
				value = i;
				break;
			}
		}
		return value;
	};

	/**
	 * 输入框disabled状态
	 */
	this.setFieldsDisabled = function() {
		var nodes = document.getElementsByName(_this.fieldName);
		for ( var i = 0, length = nodes.length; i < length; i++) {
			nodes[i].disabled = true;
		}
	};
	/**
	 * 输入框可输入状态
	 */
	this.setFieldsFill = function() {
		var nodes = document.getElementsByName(_this.fieldName);
		for ( var i = 0, length = nodes.length; i < length; i++) {
			nodes[i].readOnly = false;
			nodes[i].disabled = false;
		}
	};

	/**
	 * 设置事件监听
	 */
	this.setHandler = function(eventName, operator) {
		var nodes = document.getElementsByName(_this.fieldName);
		for ( var i = 0, length = nodes.length; i < length; i++) {
			nodes[i][eventName] = function() {
				operator(_this);
			};
		}

	};

	var init = function() {
		_this.fieldName = name;
		form_fieldName = fName;
		form_radioName = fRadioName;
		form_textArray = fTextArray;
		initValues();
	};
	init();
};
/**
 * g 文本框
 * 
 * @param name
 *            弹出窗口中文本框名称
 * @param fName
 *            表单中文本框名称
 * @returns
 */
function TextField(name, fName) {
	var _this = this;
	var fieldName = null;
	var form_fieldName = null;

	/**
	 * 初始化单选按钮的值，从表单中读取
	 */
	var initValue = function() {
		document.getElementsByName(fieldName)[0].value = getUpFieldValue(getUpFieldsByFieldval(
				form_fieldName).eq(0)).value;
	};

	/**
	 * 将弹出窗口的单选按钮的值返回表单
	 */
	this.setValueToForm = function() {
		setUpFieldValue2(getUpFieldsByFieldval(form_fieldName).eq(0), document
				.getElementsByName(fieldName)[0].value);
	};

	/**
	 * 设置输入框的值
	 */
	this.setValue = function(value) {
		document.getElementsByName(fieldName)[0].value = value ? value : "";
	};

	/**
	 * 获取文本框的值
	 */
	this.getValue = function() {
		return document.getElementsByName(fieldName)[0].value;
	};

	/**
	 * 输入框disabled状态
	 */
	this.setFieldDisabled = function() {
		var node = document.getElementsByName(fieldName)[0];
		node.className = "disabledInput";
		node.disabled = true;
	};
	/**
	 * 输入框可输入状态
	 */
	this.setFieldFill = function() {
		var node = document.getElementsByName(fieldName)[0];
		node.className = "manualInput";
		node.readOnly = false;
		node.disabled = false;
	};

	/**
	 * 输入框readOnly状态
	 */
	this.setFieldReadOnly = function() {
		var node = document.getElementsByName(fieldName)[0];
		node.disabled = false;
		node.readOnly = "readonly";
		node.className = "readOnlyInput";
	};

	/**
	 * 设置事件监听
	 */
	this.setHandler = function(eventName, operator) {
		document.getElementsByName(fieldName)[0][eventName] = function() {
			operator(_this);
		};
	};

	var init = function() {
		fieldName = name;
		form_fieldName = fName;

		initValue();
	};

	init();
};

/**
 * 供应商名称、编码更改项
 */
function ProviderChangeInfo(formWindow) {
	var _this = this;
	var fieldMap = {
		originalSupplierName : '原供应商名称',
		originalSupplierCode : '原供应商编码',
		originalSupplierBalance : '原供应商应付账款余额',
		targetSupplierName : '目标供应商名称',
		targetSupplierCode : '目标供应商编码',
		targetSupplierBalance : '目标供应商应付账款余额'
	};
	this.textFieldMap = {
		originalSupplierName : null,
		originalSupplierCode : null,
		originalSupplierBalance : null,
		targetSupplierName : null,
		targetSupplierCode : null,
		targetSupplierBalance : null
	};

	this.setValuesToForm = function() {
		for ( var name in _this.textFieldMap) {
			_this.textFieldMap[name].setValueToForm();
		}
	};

	/**
	 * 根据选择合并或者更名来控制是否可以输入或者readonly
	 */
	this.fieldStateSet = function(locationSpecifiedValue, init) {
		_this.textFieldMap.originalSupplierName.setFieldReadOnly();
		_this.textFieldMap.originalSupplierCode.setFieldFill();
		_this.textFieldMap.originalSupplierBalance.setFieldFill();

		if (locationSpecifiedValue === 0) {
			_this.textFieldMap.targetSupplierCode.setFieldDisabled();
			_this.textFieldMap.targetSupplierCode.setValue("");
			_this.textFieldMap.targetSupplierName.setFieldFill();
			_this.textFieldMap.targetSupplierBalance.setFieldDisabled();
			if (!init)
				formWindow
						.queryOriginalSupplier(_this.textFieldMap.originalSupplierCode);
		} else if (locationSpecifiedValue === 1) {
			_this.textFieldMap.targetSupplierCode.setFieldFill();
			_this.textFieldMap.targetSupplierName.setFieldReadOnly();
			_this.textFieldMap.targetSupplierBalance.setFieldFill();
			if (!init)
				formWindow
						.queryOriginalSupplier(_this.textFieldMap.targetSupplierCode);
		}
	};

	var init = function() {
		for ( var name in fieldMap) {
			var textField = new TextField(name, fieldMap[name]);
			_this.textFieldMap[name] = textField;
		}

		_this.textFieldMap.originalSupplierCode.setHandler('onchange',
				function(textFiled) {
					formWindow.queryOriginalSupplier(textFiled, 'changeValue');
				});
		_this.textFieldMap.targetSupplierCode.setHandler('onchange', function(
				textFiled) {
			formWindow.queryTargetSupplier(textFiled, 'changeValue');
		});
	};

	init();
};

function FormWindow() {
	this.providerInformation = null;
	var _this = this;
	var providerInformationJSON = null;
	/**
	 * 单选框和表单中字段的对应 radioMap[name].instance
	 */
	var radioMap = {
		locationSpecified : {
			mapping : [ '地点指定', '是否更名' ],
			textValue : [ '更名（原供应商地点重新指定给新供应商）', '合并（新老供应商地点信息合并）' ]
		},
		groupManage : {
			mapping : [ null, '集团管控' ],
			textValue : []
		},
		invoice : {
			mapping : [ null, '发票传送' ],
			textValue : []
		},
		purchaseOrder : {
			mapping : [ null, '采购订单传送' ],
			textValue : []
		},
		isInfoChange : {
			mapping : [ '目标供应商信息', '信息是否改变' ],
			textValue : [ '信息变更', '信息不变' ]
		}
	};
	var locationSpecifiedValue = null;
	var isInfoChangeValue = null;
	var providerChangeInfo = null;

	/**
	 * 触发选择变更或者合并单选框的事件处理
	 */
	var onLocationSpecifiedClick = function(radio, init) {
		var value = radio.getValue();
		if (value !== -1) {
			if (locationSpecifiedValue === null) {
				for ( var name in radioMap) {
					radioMap[name].instance.setFieldsFill();
				}
			}
			if (value !== locationSpecifiedValue) {
				locationSpecifiedValue = value;
				providerChangeInfo.fieldStateSet(value, init);
				providerInformationJSON = null;
				if (!init) {
					_this.providerInformation.setValues(null);
					providerInformationJSON = null;
				}
			}
		}
	};

	/**
	 * 触发选择是否更改供应商信息单选框的事件处理
	 */
	var onIsInfoChangeClick = function(radio, init) {
		var value = radio.getValue();
		if (value !== -1) {
			if (value !== isInfoChangeValue) {
				isInfoChangeValue = value;
				if (value === 0) {
					_this.providerInformation.setFieldsFill();
					// showAptitude();
				} else if (value === 1) {
					_this.providerInformation.setFieldsReadOnly();
					if (init) {
						_this.providerInformation.initValues();
					} else {
						_this.providerInformation
								.setValues(providerInformationJSON);
					}
					// resetAptitude();
				}
			}
		}
	};

	/**
	 * 查询原供应商名称名称
	 */
	this.queryOriginalSupplier = function(textFiled, changeValue) {
		var targetSupplierCode = document
				.getElementsByName("targetSupplierCode")[0].value.replace(/ /g,
				'');
		// alert();
		var value = textFiled.getValue().replace(/ /g, '');
		textFiled.setValue(value);
		if (changeValue) {
			providerChangeInfo.textFieldMap.originalSupplierName.setValue("");
			_this.providerInformation.setValues(null);
			providerInformationJSON = null;
		}
		if (value === '') {
			if (changeValue) {
				alert("原供应商编码不能为空");
			}
		} else if (value == targetSupplierCode) {
			alert("目标供应商编码不能和原供应商编码相同");
		} else {
			_ajax(
					value,
					(radioMap.locationSpecified.instance.getValue() === 0 ? 2
							: 1),
					function(obj) {
						providerChangeInfo.textFieldMap.originalSupplierName
								.setValue(obj.providerName);
						if (radioMap.locationSpecified.instance.getValue() === 0)
							_this.providerInformation.setValues(obj);
						providerInformationJSON = obj;
					});
		}
	};
	/**
	 * 查询目标供应商名称名称
	 */
	this.queryTargetSupplier = function(textFiled, changeValue) {
		var originalValue = document.getElementsByName("originalSupplierCode")[0].value
				.replace(/ /g, '');
		var value = textFiled.getValue().replace(/ /g, '');
		textFiled.setValue(value);
		if (changeValue) {
			providerChangeInfo.textFieldMap.targetSupplierName.setValue("");
			_this.providerInformation.setValues(null);
			providerInformationJSON = null;
		}
		if (value === '') {
			alert("目标供应商编码不能为空");
		} else if (value == originalValue) {
			alert("目标供应商编码不能和原供应商编码相同");
		} else {
			_ajax(
					value,
					(radioMap.locationSpecified.instance.getValue() === 0 ? 1
							: 2),
					function(obj) {
						providerChangeInfo.textFieldMap.targetSupplierName
								.setValue(obj.providerName);
						if (radioMap.locationSpecified.instance.getValue() === 1)
							_this.providerInformation.setValues(obj);
						providerInformationJSON = obj;
					});
		}
	};

	this.setValuesToForm = function() {
		var success = false;

		if (_this.providerInformation.checkNotNull()) {

			_this.providerInformation.setValuesToForm();
			providerChangeInfo.setValuesToForm();
			for ( var name in radioMap) {
				console.info("name="+name)
				radioMap[name].instance.setValueToForm();
			}
			var value = radioMap.locationSpecified.instance.getValue();
			console.log("value = "+value);
			if (value !== -1) {
				setUpFieldValue2(getUpFieldsByFieldval("地点指定").eq(0),
						radioMap.locationSpecified.textValue[value]);
			}
			// var companySelect = document.getElementsByName("company")[0];
			// if (companySelect.value != "") {
			setUpFieldValue2(getUpFieldsByFieldval("更名合并供应商_制造部选择器").eq(0),
					getUpFieldValue(getUpFieldsByFieldval("单位选择器").eq(0)).value);// companySelect.value;
			// var text =
			// companySelect.options[companySelect.selectedIndex].text;
			// up_doc.getElementById("更名合并供应商_制造部选择器").value = up_doc
			// .getElementById("单位选择器").value;// text;
			setUpFieldValue2(getUpFieldsByFieldval("制造部").eq(0),
					getUpFieldValue(getUpFieldsByFieldval("单位选择器").eq(0)).value);// text;

			success = true;
			// } else {
			// alert("制造部名称不能为空");
			// }
		}

		return success;
	};

	this.onCompanySelectChange = function() {
		_this.providerInformation.setValues();

		var textFields = providerChangeInfo.textFieldMap;
		for ( var name in textFields) {
			textFields[name].setValue("");
		}

	};

	this.allowNull = function() {
		var radioValue = radioMap.locationSpecified.instance.getValue();
		// if (radioValue == 0) {
		// up_doc.getElementById("目标供应商编码").is_null = 'true';
		// up_doc.getElementById("目标供应商应付账款余额").is_null = 'true';
		// } else {
		// up_doc.getElementById("目标供应商编码").is_null = 'false';
		// up_doc.getElementById("目标供应商应付账款余额").is_null = 'false';
		// }
	};

	/**
	 * 相当于构造函数
	 */
	var init = function() {
		_this.providerInformation = new ProviderInformation();
		providerChangeInfo = new ProviderChangeInfo(_this);
		for ( var name in radioMap) {
			var radio = new RadioField(name, radioMap[name].mapping[0],
					radioMap[name].mapping[1], radioMap[name].textValue);
			radioMap[name].instance = radio;
			// radioArray.push(radio);
		}
		radioMap.locationSpecified.instance.setHandler('onclick',
				onLocationSpecifiedClick);
		radioMap.isInfoChange.instance.setHandler('onclick',
				onIsInfoChangeClick);
		onLocationSpecifiedClick(radioMap.locationSpecified.instance, 'init');
		onIsInfoChangeClick(radioMap.isInfoChange.instance, 'init');

	};

	init();
};

function onCompanySelectChange() {
	formWindow.onCompanySelectChange();
}

function createAjax(params, url, operator) {
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange = function() {
		operator(xmlhttp, function() {
			document.getElementById("lodingDiv").style.display = "none";
		});
	};
	document.getElementById("lodingDiv").style.display = "";
	xmlhttp.open("get", url, true);
	xmlhttp.send();
};

window.onload = function() {
	// if (up_doc.getElementById("总办填写表单_")) {
	// document.getElementsByName("company")[0].value = up_doc
	// .getElementById("更名合并供应商_制造部选择器")['default'];
	// document.getElementsByName("company")[0].disabled = false;
	// document.getElementsByName("company")[0].className = "manualInput";
	// } else {
	// document.getElementsByName("company")[0].value = up_doc
	// .getElementById("单位选择器")['default'];
	// document.getElementsByName("company")[0].disabled = true;
	// document.getElementsByName("company")[0].className = "readOnlyInput";
	// }
	formWindow = new FormWindow();
	// initAptitude();
	document.getElementById("submitButton").onclick = function() {
		if (document.getElementsByName("locationSpecified")[0].checked) {

			var providerName = document.getElementsByName("targetSupplierName")[0].value;

			if (!checkAndReplaceProviderName(document
					.getElementsByName("targetSupplierName")[0])) {
				return;
			}

			checkInputLength();

			providerName = document.getElementsByName("targetSupplierName")[0].value;

			createAjax(
					"",
					"./oa2uapController.do?method=checkProviderNameIsExist&providerName="
							+ (encodeURIComponent(providerName)) + "&temp="
							+ Math.random(),
					function(xmlhttp, hideLodingDiv) {
						if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
							hideLodingDiv();
							text = xmlhttp.responseText;
							if (text == 'error') {
								alert("异常，无法验证供应商名称是否已存在");
							} else {
								var resultJSON = eval("(" + text + ")");
								if (resultJSON.success) {
									if (!resultJSON.code
											|| resultJSON.code == ''
											|| resultJSON.code == document
													.getElementsByName("originalSupplierCode")[0].value) {

										if (formWindow.setValuesToForm()) {
											formWindow.allowNull();
											fy_dialog_close();
										}
									} else {
										alert("目标供应商名称已存在");
									}
								} else {
									alert("异常，无法验证供应商名称是否已存在");
								}
							}
						}
					});
		} else {
			if (formWindow.setValuesToForm()) {
				formWindow.allowNull();
				fy_dialog_close();
			}
		}
	};
};

var formWindow = null;
